import pdfplumber
import re
import os
import pandas as pd
 

def re_text(bt, text,):
    m1 = re.search(bt, text)
    if m1 is not None:
        return re_block(m1[0])
 
 
def re_block(text):
    return text.replace(' ', '').replace('　', '').replace('）', '').replace(')', '').replace('：', ':')
 
 
def get_pdf(dir_path):
    pdf_file = []
    for root, sub_dirs, file_names in os.walk(dir_path):
        for name in file_names:
            if name.endswith('.pdf'):
                filepath = os.path.join(root, name)
                pdf_file.append(filepath)
    return pdf_file

def read_invoice(pdf_text):
        pupiao = re_text(re.compile(r'[\u4e00-\u9fa5]+电子普通发票.*?'), pdf_text)
        zhuanpiao = re_text(re.compile(r'[\u4e00-\u9fa5]+专用发票.*?'), pdf_text)
        fapiaodaima = re_text(re.compile(r'发票代码(.*\d+)'), pdf_text) #普票独有
        fapiaohaoma = re_text(re.compile(r'发票号码(.*\d+)'), pdf_text)
        kaipiaoriqi = re_text(re.compile(r'开票日期(.*)'), pdf_text)
        jiaoyan = re_text(re.compile(r'校 验 码\s*[:：]\s*([a-zA-Z0-9 ]+)'), pdf_text) #普票独有
        company = re.findall(re.compile(r'名.*称\s*[:：]\s*([\u4e00-\u9fa5]+)'), pdf_text)
        gongsi = re_block(company[len(company)-1])
        shibiehao = re.findall(re.compile(r'纳税人识别号\s*[:：]\s*([a-zA-Z0-9]+)'), pdf_text)
        gongsi_shibiehao = re_block(shibiehao[len(shibiehao)-1])
        xiaoxie = re_text(re.compile(r'小写.*(.*[0-9.]+)'), pdf_text)
        jinee = float(re.sub(r'[^0-9.]', '', xiaoxie))
        print('--------------------------------------------------------')
        
        if pupiao:
            print(pupiao)
            print(fapiaodaima)
            print(fapiaohaoma)
            print(kaipiaoriqi)
            print(jiaoyan)
            lst = [gongsi,jinee,kaipiaoriqi[5:],fapiaohaoma[5:],gongsi_shibiehao,fapiaodaima[5:],jiaoyan[4:],]
        else:
            print(zhuanpiao)
            print(fapiaohaoma)
            print(kaipiaoriqi)
            lst = [gongsi,jinee,kaipiaoriqi[5:],fapiaohaoma[5:],gongsi_shibiehao]
        #lst = [gongsi,jinee,kaipiaoriqi[5:],fapiaohaoma[5:],gongsi_shibiehao]
        print(f'金额：{jinee}')
        print(gongsi)
        print(f'纳税人识别号：{gongsi_shibiehao}')
        print('--------------------------------------------------------')  
        return lst
        

def read(filenames):
    inv_list = []
    inv_list.append(['公司名称','金额','开票日期','发票号码','纳税人识别号','发票代码','校验码'])
    for filename in filenames:
        print(filename)
        with pdfplumber.open(filename) as pdf:
            first_page = pdf.pages[0]
            pdf_text = first_page.extract_text()
            if '发票' not in pdf_text:continue #不是发票则跳过
            lst = read_invoice(pdf_text)
            inv_list.append(lst)
    df = pd.DataFrame(inv_list,columns=inv_list[0],dtype=str)
    df.drop(0,inplace=True)
    df['金额']=df['金额'].astype(float)
    
    return df

if __name__ == '__main__':
    filenames = get_pdf(os.getcwd())
    df=read(filenames)
    df['金额'].sum()
